package com.chen.dataupload.task;

import com.chen.dataupload.data.CreateData;
import com.chen.dataupload.util.HttpClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.time.LocalDateTime;

@Component
@Configuration
@EnableScheduling
public class DataUploadTask implements SchedulingConfigurer {

    String url = "http://127.0.0.1:8080/getData";


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
                    System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime());

                    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
                    String json = "";
                    try {
                        json = CreateData.createJsonData();
                        params.add("data", json);
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                    HttpClient.sendPostRequest(url,params);
                },
                triggerContext -> {
                    String cron = "0/5 * * * * ?";
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                });
    }
}
